package com.lingnan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/debug")
public class RedisDebugController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Redis连接测试端点
     */
    @GetMapping("/redis")
    public ResponseEntity<Map<String, Object>> testRedisConnection() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 测试连接性
            String pingResult = redisTemplate.getConnectionFactory().getConnection().ping();
            result.put("ping", pingResult);

            // 测试读写能力
            String testKey = "connection_test:" + System.currentTimeMillis();
            redisTemplate.opsForValue().set(testKey, "success", 10, TimeUnit.SECONDS);
            Object value = redisTemplate.opsForValue().get(testKey);
            result.put("readWriteTest", "success".equals(value) ? "PASS" : "FAIL");

            // 获取连接信息
            RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
            if (factory instanceof LettuceConnectionFactory) {
                LettuceConnectionFactory lettuceFactory = (LettuceConnectionFactory) factory;
                result.put("host", lettuceFactory.getHostName());
                result.put("port", lettuceFactory.getPort());
                result.put("database", lettuceFactory.getDatabase());
            }

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("error", e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}